package com.wxd.framework.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.wxd.framework.common.FrameConstants;
import com.wxd.framework.common.Criteria;
import com.wxd.framework.common.data.DateJsonValueProcessor;
import com.wxd.framework.common.page.Pagination;
import com.wxd.framework.common.web.RequestUtils;
import com.wxd.framework.common.web.ResponseUtils;
import com.wxd.framework.common.web.session.SessionProvider;
import com.wxd.framework.entity.User;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class BaseController {
	
	@Autowired
	protected SessionProvider session;
	
	/**
	 * 获取当前登录人员
	 * @param request
	 * @return
	 */
	protected User getCurrUser(HttpServletRequest request){
		User user = (User) session.getAttributeObject(request, FrameConstants.SESSON_KEY_CURRUSER);
		return user;
	}
	
	/**
	 * 获取分页信息
	 * @param request
	 * @return
	 */
	protected Criteria getPaginationCriteria(HttpServletRequest request){
		String pageStr = RequestUtils.getQueryParam(request, "page");
		String rowsStr = RequestUtils.getQueryParam(request, "rows");
		Criteria criteria = new Criteria();
		int pageSize = 20;
		int pageNo = 1;
		if (StringUtils.isNotBlank(pageStr)) {
			pageNo = Integer.parseInt(pageStr);
			criteria.setPageNo(pageNo);
		}
		if (StringUtils.isNotBlank(rowsStr)) {
			pageSize = Integer.parseInt(rowsStr);
			criteria.setPageSize(pageSize);
		}
		return criteria;
	}
	
	/**
	 * 返回对象列表
	 * @param list
	 * @param response
	 */
	protected <T> void renderListWithBoolFlag(List<T> list, Boolean flag, HttpServletResponse response) {
		JSONArray arr = JSONArray.fromObject(list);
		JSONObject job = new JSONObject();
		job.element("rows", arr);
		job.element("flag", flag);
		ResponseUtils.renderJson(response, job.toString());
	}
	
	/**
	 * 返回对象列表（头部添加一个指定元素）
	 * @param list
	 * @param empty
	 * @param response
	 */
	protected <T> void renderListWithEmpty(List<T> list, T empty, HttpServletResponse response){
		JSONArray arr = JSONArray.fromObject(list);
		arr.add(0, empty);
		ResponseUtils.renderJson(response, arr.toString());
	}
	
	/**
	 * 返回对象列表
	 * @param list
	 * @param response
	 */
	protected <T> void renderList(List<T> list, HttpServletResponse response){
		JSONArray arr = JSONArray.fromObject(list);
		ResponseUtils.renderJson(response, arr.toString());
	}
	
	/**
	 * 返回对象列表（带日期类型）（头部添加一个指定元素）
	 * @param list
	 * @param empty
	 * @param response
	 */
	protected <T> void renderDateListWithEmpty(List<T> list, T empty, HttpServletResponse response){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		JSONArray arr = JSONArray.fromObject(list,jsonConfig);
		arr.add(0, empty);
		ResponseUtils.renderJson(response, arr.toString());
	}
	
	/**
	 * 返回对象列表（带日期类型）
	 * @param list
	 * @param response
	 */
	protected <T> void renderDateList(List<T> list, HttpServletResponse response){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		JSONArray arr = JSONArray.fromObject(list,jsonConfig);
		ResponseUtils.renderJson(response, arr.toString());
	}
	
	protected void renderPagination(Pagination dataPage, HttpServletResponse response){
		List list =  dataPage.getList();
		JSONArray arr = JSONArray.fromObject(list);
		JSONObject job = new JSONObject();
		job.element("rows", arr);
		job.element("total", dataPage.getTotalCount());
		ResponseUtils.renderJson(response, job.toString());
	}
	
	protected void renderDatePagination(Pagination dataPage, HttpServletResponse response){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		
		List list = dataPage.getList();
		JSONArray arr = JSONArray.fromObject(list,jsonConfig);
		JSONObject job = new JSONObject();
		job.element("rows", arr);
		job.element("total", dataPage.getTotalCount());
		ResponseUtils.renderJson(response, job.toString());
	}
	
	/**
	 * 返回错误对象
	 * @param e
	 * @param response
	 */
	protected void renderException(Exception e, HttpServletResponse response) {
		JSONObject job = new JSONObject();
		job.element(FrameConstants.JSON_FLAG_NAME, FrameConstants.JSON_FLAG_FAIL);
		job.element(FrameConstants.JSON_ERROR_MESSAGE, e.getMessage());
		ResponseUtils.renderJson(response, job.toString());
	}
	
	/**
	 * 执行失败后的json返回
	 * @param response
	 */
	protected void renderJsonExcuteFail(String errmsg, HttpServletResponse response){
		JSONObject job = new JSONObject();
		job.element(FrameConstants.JSON_FLAG_NAME, FrameConstants.JSON_FLAG_FAIL);
		job.element(FrameConstants.JSON_ERROR_MESSAGE, errmsg);
		ResponseUtils.renderJson(response, job.toString());
	}
	
	
	/**
	 * 正确执行后的json返回
	 * @param response
	 */
	protected void renderJsonExcuteSuccess(HttpServletResponse response){
		JSONObject job = new JSONObject();
		job.element(FrameConstants.JSON_FLAG_NAME, FrameConstants.JSON_FLAG_SUCCESS);
		ResponseUtils.renderJson(response, job.toString());
	}
	
	/**
	 * 返回字符串
	 * @param response
	 */
	protected void renderText(HttpServletResponse response, String text){
		ResponseUtils.renderText(response, text);
	}
	
	/**
	 * 返回一个对象
	 * @param object
	 * @param response
	 */
	protected <T> void renderOneObject(T object, HttpServletResponse response){
		JSONObject job = new JSONObject();
		if (object != null) {
			job = JSONObject.fromObject(object);
			job.element(FrameConstants.JSON_FLAG_NAME, FrameConstants.JSON_FLAG_SUCCESS);
		}else {
			job.element(FrameConstants.JSON_FLAG_NAME, FrameConstants.JSON_FLAG_FAIL);
			job.element(FrameConstants.JSON_ERROR_MESSAGE, "操作对象无效！");
		}
		ResponseUtils.renderJson(response, job.toString());
	}

	//----------------------------------------------------------------
	protected OutputStream getExcelOutputStream(String fileName, HttpServletResponse response) throws IOException{
		OutputStream outputStream = response.getOutputStream();
		fileName = new String(fileName.getBytes("GB2312"), "8859_1") + ".xls";
		response.reset(); // 清空输出流
		response.setHeader("Content-disposition", "attachment; filename=" + fileName); // 设定输出文件头
		response.setContentType("application/msexcel"); // 定义输出类型
		return outputStream;
	}
}
